<?php


namespace app\api\controller\app\online;

use addons\unidrink\extend\Hashids;
use addons\unidrink\model\Bill;
use addons\unidrink\model\Config;
use app\admin\model\Banner;
use app\admin\model\City;
use app\admin\model\online\Onlineshopprofit;
use app\admin\model\Org;
use app\admin\model\OrgIndexNotice;
use app\admin\model\OrgNotice;
use app\admin\model\Roomclean;
use app\admin\model\Shop;
use app\admin\model\shop\Room;
use app\admin\model\Shopmno;
use app\admin\model\Shoporder;
use app\admin\model\Shoporderprofit;
use app\admin\model\Shoproom;
use app\admin\model\Shoproombook;
use app\admin\model\unidrink\Category;
use app\admin\model\unidrink\Goods;
use app\admin\model\unidrink\Product;
use app\admin\model\Userallbalance;
use app\admin\model\Userbalance;
use app\admin\model\Userorderprofit;
use app\admin\model\Usertuan;
use app\admin\model\Userweixin;
use app\api\service\VbillService;
use app\common\controller\Api;

use fast\Http;
use think\Db;
use think\Exception;
use think\Hook;
use think\Loader;
use function EasyWeChat\Kernel\Support\get_client_ip;


/**
 */
class Index extends Api
{
    protected $noNeedLogin = ['getRoomList','cateList','sxfOrderCallback','getShopInfo','sxfOrderCallbackV2'];
    protected $noNeedRight = '*';


    public function getShopInfo()
    {

        $id = $this->request->param('id');
        $shopModel = new Shop();
        $shop = $shopModel->where('id',$id)->find();
        $this->success('',$shop['name']);
    }

    public function _initialize()
    {
        parent::_initialize();

    }

    public function sxfOrderCallback()
    {

        $param = file_get_contents("php://input");

        $ret = json_decode($param, true);
        $amt = $ret['amt'];
        $out_trade_no = $ret['ordNo'];
        $transactionId = $ret['transactionId'];
        if ($ret['bizCode'] == '0000') {


            $back = array();
            $back['code'] = "success";
            $back['msg'] = "成功";
            echo json_encode($back);

            $orderModel = new \addons\unidrink\model\Order(); //($message['out_trade_no']);
            $order = $orderModel->where(['out_trade_no' => $out_trade_no])->find();

            // 充值订单
            $billModel = new Bill();
            $bill = $billModel->where(['out_trade_no' => $out_trade_no])->find();

            $key = $out_trade_no;
            $value = $this->redis->get($key);
            if(!$value){
                $this->redis->set($key,1);

                $unShopModel = new \app\admin\model\unidrink\Shop();
                $ushop = $unShopModel->where('id',$order['shop_id'])->find();
                $shopModel = new Shop();
                $shop = $shopModel->where('id',$ushop['shop_id'])->find();

                $fee = $order['order_price']*0.006;
                $amount = $order['order_price'] - $order['order_price']*0.006;
                $onlineShopProfitModel = new \app\admin\model\Onlineshopprofit();
                $onlineShopProfitModel->insert(['order_id'=>$order['id'],'shop_id'=>$shop['id'],'user_id'=>$shop['user_id'],'amount'=>$amount,'create_time'=>time(),'fee'=>$fee]);

                Hook::exec('addons\\unidrink\\behavior\\Order', 'paid_success', $order, ['pay_type' => \addons\unidrink\model\Order::PAY_WXPAY]);
                Hook::exec('addons\\unidrink\\behavior\\Bill', 'paid_success', $bill, ['pay_type' => Bill::PAY_WXPAY]);

            }

        }
    }

    public function sxfOrderCallbackV2()
    {

        $param = file_get_contents("php://input");

        $ret = json_decode($param, true);
        var_dump($ret);
        $amt = $ret['amt'];
        $out_trade_no = $ret['ordNo'];
        $transactionId = $ret['transactionId'];
        if ($ret['bizCode'] == '0000') {


            $back = array();
            $back['code'] = "success";
            $back['msg'] = "成功";
            echo json_encode($back);

            $orderModel = new \addons\unidrink\model\Order(); //($message['out_trade_no']);
            $order = $orderModel->where(['out_trade_no' => $out_trade_no])->find();

            // 充值订单
            $billModel = new Bill();
            $bill = $billModel->where(['out_trade_no' => $out_trade_no])->find();
            echo "11111111\n";

            $key = $out_trade_no;
            $value = $this->redis->get($key);
            echo "222222222\n";
            if(!$value){
                $this->redis->set($key,1);
                echo "33333333\n";
                Hook::exec('addons\\unidrink\\behavior\\Order', 'paid_success', $order, ['pay_type' => \addons\unidrink\model\Order::PAY_WXPAY]);
                Hook::exec('addons\\unidrink\\behavior\\Bill', 'paid_success', $bill, ['pay_type' => Bill::PAY_WXPAY]);
                echo "4444444\n";

                $unShopModel = new \app\admin\model\unidrink\Shop();
                $ushop = $unShopModel->where('id',$order['shop_id'])->find();
                $shopModel = new Shop();
                $shop = $shopModel->where('id',$ushop['shop_id'])->find();
                echo "55555555\n";

                $amount = $order['order_price'] - $order['order_price']*0.006;
                echo "写入收益金额==》".$amount;
                echo "666666666666\n";
                $onlineShopProfitModel = new \app\admin\model\Onlineshopprofit();
                $onlineShopProfitModel->insert(['order_id'=>$order['id'],'shop_id'=>$shop['id'],'user_id'=>$shop['user_id'],'amount'=>$amount,'create_time'=>time()]);
                echo "7777777777777\n";
            }

        }
    }

    public function addOrder()
    {

        $data = $this->request->post();
//        try {
//            $validate = Loader::validate('\\addons\\unidrink\\validate\\Order');
//            if (!$validate->check($data, [], 'submit')) {
//                throw new Exception($validate->getError());
//            }


            Db::startTrans();

            // 判断创建订单的条件
//            if (empty(Hook::get('create_order_before'))) {
//                Hook::add('create_order_before', 'addons\\unidrink\\behavior\\Order');
//            }
            // 减少商品库存，增加"已下单未支付数量"
//            if (empty(Hook::get('create_order_after'))) {
//                Hook::add('create_order_after', 'addons\\unidrink\\behavior\\Order');
//            }

            $user = $this->auth->getUser();
            $orderModel = new \addons\unidrink\model\Order();
            $shop_id = $data['shop_id'];
            $shopModel = new \addons\unidrink\model\Shop();
            $shop = $shopModel->where('shop_id',$shop_id)->find();
            $data['ktv_shop_id'] = $shop_id;
            $data['shop_id'] = $shop['id'];




            $result = $orderModel->createOrder($user['id'], $data);



            Db::commit();


//        } catch (Exception $e) {
//            Db::rollback();
//            $this->error($e->getMessage(), false);
//        }



        $out_trade_no = $result['out_trade_no'];

        //解密
        $id = $result['order_id'];
        $order_id = $id;
        $order = $orderModel->where('out_trade_no',$out_trade_no)->find();
        $orderModel->where('id',$order['id'])->update(['room_id'=>$data['room_id']]);


        $ktvShopModel = new Shop();
        $ktvShop = $ktvShopModel->where('id',$shop['shop_id'])->find();

        $userwxModel = new Userweixin();
        $wx = $userwxModel->where('user_id', $user['id'])->find();
        $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/online/index/sxfOrderCallback";

        $orgModel = new Org();
        $org = $orgModel->where('id', $ktvShop['org_id'])->find();


        $mno = $shop['mno'];
        if($mno == ''){
            $mno = $org['mno'];
        }
        $req['mno'] = $mno;
        $req['ordNo'] = $out_trade_no;
        $req['amt'] = formatMoney($order['order_price']);

        $req['payType'] = "WECHAT";
        $req['payWay'] = "03";
        $req['subAppid'] = "wx4abd56997bacbaee";
        $req['userId'] = $wx['openid'];

        $req['subject'] = "点餐购买";
        $req['tradeSource'] = "01";
        $req['trmIp'] = get_client_ip();
        $req['notifyUrl'] = $url;


        $vbillService = new VbillService();
        $res = $vbillService->jsApi($req);
        $result = json_decode($res, true);
        $bizCode = $result['respData']['bizCode'];
        $bizMsg = $result['respData']['bizMsg'];

        if ($bizCode == '0000') {
            $info['order_no'] = $out_trade_no;
            $info['order_id'] = $order_id;

            $info['payInfo'] = $result['respData'];
            $this->success('', $info);

        } else {
            $this->error($bizMsg);
        }



    }

    public function getRoomList()
    {

        $id = $this->request->param('shop_id');
        $room_id = $this->request->param('room_id');
        $roomModel = new Room();
        $list = $roomModel->where('shop_id',$id)->select();
        $this->success('',$list);
    }

    public function detail()
    {
        $order_id = $this->request->param('id', 0);

        $user  = $this->auth->getUser();
        try {
            $orderModel = new \addons\unidrink\model\Order();
            $order = $orderModel
                ->with([
                    'products' => function ($query) {
                        $query->field('id,order_id,image,number,price,spec,title,product_id');
                    },
                    'extend' => function ($query) {
                        $query->field('id,order_id,address_id,address_json');
                    },
                    'evaluate' => function ($query) {
                        $query->field('id,order_id,product_id');
                    },
                    'shop' => function ($query) {
                        $query->field('id,name,mobile,lng,lat,address_map,address');
                    }
                ])
                ->where(['id' => $order_id, 'user_id' => $user['id']])->find();


            if ($order) {
                $order = $order->append(['paidtime', 'receivedtime', 'commentedtime', 'pay_type_text', 'type_text'])->toArray();

                // 送货地址
                if ($order['type'] == \addons\unidrink\model\Order::BUY_TYPE_TAKEOUT) {
                    $address = json_decode($order['extend']['address_json'], true);
                    $order['address'] = $address;
                } else {
                    $order['address'] = [];
                }

                // 是否已评论
                $evaluate = array_column($order['evaluate'], 'product_id');
                foreach ($order['products'] as &$product) {
                    $product['image'] = Config::getImagesFullUrl($product['image']);
                    if (in_array($product['id'], $evaluate)) {
                        $product['evaluate'] = true;
                    } else {
                        $product['evaluate'] = false;
                    }
                }

                // 订单状态
                $order['order_status_text'] = $orderModel->orderStatusText($order);

                unset($order['evaluate']);
                unset($order['extend']);
            }

            $shopRoomModel = new Shoproom();
            $room = $shopRoomModel->where('id',$order['room_id'])->find();
            $ktvShopModel = new Shop();
            $ktv = $ktvShopModel->where('id',$room['shop_id'])->find();
            $order['room_name'] = $room['name'];
            $order['shop_name'] = $ktv['name'];

            $this->success('', $order);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }

    }



    public function cateList()
    {

        $shop_id = $this->request->param('shop_id');

        $keyword = $this->request->param('keyword');
        $shopModel = new \app\admin\model\unidrink\Shop();
        $shop = $shopModel->where('shop_id',$shop_id)->find();

        $shop_id = $shop['id'];
        $categoryModel = new \addons\unidrink\model\Category();
        $where = array();
        if($keyword != ""){
            $all = $categoryModel
                ->with(['goodsList' => function($query) use ($shop_id,$keyword) {
                    $query
                        ->where(['switch' => \addons\unidrink\model\Product::SWITCH_ON])
                        ->where('shop_id = '.Product::ALL_SHOP.' OR FIND_IN_SET(:shop_id, shop_id)', ['shop_id' => $shop_id])
                        ->where('title','like','%'.$keyword.'%')
                        ->field('id,category_id,image,sales_price,title as name,`desc`,use_spec,real_sales,sales,specList,specTableList,stock')
                        ->order('weigh DESC');
                }])
                ->where('type','product')
                ->where('status','normal')
                ->where('shop_id = '.\addons\unidrink\model\Category::ALL_SHOP.' OR FIND_IN_SET(:shop_id, shop_id)', ['shop_id' => $shop_id])
                ->field('id,name,image as icon,weigh as sort')
                ->order('weigh ASC')
                //->cache('menu-goods-' . $shop_id,10)
                ->select();
        }else{
            $all = $categoryModel
                ->with(['goodsList' => function($query) use ($shop_id) {
                    $query
                        ->where(['switch' => \addons\unidrink\model\Product::SWITCH_ON])
                        ->where('shop_id = '.Product::ALL_SHOP.' OR FIND_IN_SET(:shop_id, shop_id)', ['shop_id' => $shop_id])
                        ->field('id,category_id,image,sales_price,title as name,`desc`,use_spec,real_sales,sales,specList,specTableList,stock')
                        ->order('weigh DESC');
                }])
                ->where('type','product')
                ->where('status','normal')
                ->where('shop_id = '.\addons\unidrink\model\Category::ALL_SHOP.' OR FIND_IN_SET(:shop_id, shop_id)', ['shop_id' => $shop_id])
                ->field('id,name,image as icon,weigh as sort')
                ->order('weigh ASC')
                //->cache('menu-goods-' . $shop_id,10)
                ->select();
        }


        if ($all) {
            $all = collection($all)->toArray();
        }

        $this->success('',$all);
    }




    public function getOrders()
    {
        $page = $this->request->param('page', 1);
        $pagesize = $this->request->param('pagesize', 10);
        $user = $this->auth->getUser();
        try {

            $orderModel = new \addons\unidrink\model\Order();
            $result = $orderModel->getOrdersByType($user['id'], $page, $pagesize);
            $this->success('', $result);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }






}
